package top.haijunit.springboot.bucket.springsecurity01.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;
import top.haijunit.springboot.bucket.springsecurity01.service.UserService;

import javax.sql.DataSource;

/**
 * @Author 百旺张
 * @Date 2021/11/8
 * @Description
 */
@RequiredArgsConstructor
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserService userService;
    private final DataSource dataSource;


    @Bean
    PasswordEncoder password() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }

    @Bean
    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }


    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(password());
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.formLogin()
                .loginPage("/login.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/index.html")
                .permitAll()
                .and().authorizeRequests()
                // 不需要认证，放行
                .antMatchers("/login","/login.html","/403.html","*.js","*.css")
                .permitAll()
                // 指定权限
                .antMatchers("/admin").hasAuthority("admin")
                .antMatchers("/user").hasAnyAuthority("admin","user")
                // 指定角色
                .antMatchers("/manager").hasRole("manager")
                .antMatchers("/maintainer").hasAnyRole("manager","maintainer")
                .anyRequest().authenticated()
                .and().rememberMe()
                .tokenRepository(persistentTokenRepository())
                .tokenValiditySeconds(60)
                .userDetailsService(userService)
                // 关闭csrf防护 跨站请求伪造
                .and().csrf().disable();
        http.exceptionHandling().accessDeniedPage("/403.html.html"); // 没有权限跳转界面
    }
}
